package jface.solutions.util;

import jface.data.Person;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

public class AgeEditingSupportExercise extends EditingSupport {

	private TableViewer viewer;

	public AgeEditingSupportExercise(TableViewer viewer) {
		super(viewer);
		this.viewer = viewer;
	}

	protected CellEditor getCellEditor(Object element) {
		TextCellEditor editor = new TextCellEditor(viewer.getTable());
		return editor;
	}

	protected boolean canEdit(Object element) {
		return true;
	}

	protected Object getValue(Object element) {
		return String.valueOf(((Person) element).getAge());
	}

	protected void setValue(Object element, Object value) {
		Person person = (Person) element;
		int newAge;
		try {
			newAge = Integer.parseInt(String.valueOf(value));
		} catch (NumberFormatException e) {
			MessageBox mb = new MessageBox(new Shell(), SWT.ICON_ERROR);
			mb.setMessage("Only numbers allowed, '"+value+"' is not a number.");
			mb.open();					
			return;
		}
		if(newAge < 0){
			MessageBox mb = new MessageBox(new Shell(), SWT.ICON_ERROR);
			mb.setMessage("Only positive values allowed, '"+newAge+"' is negative.");
			mb.open();					
			return;
		}

		person.setAge(newAge);
		viewer.refresh();
	}
}
